package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
)

// 获取管理员角色权限信息
func GetUserAdminRoleAuthorityInfo(p map[string]interface{}) *models.UserAdminRoleAuthority {
	o := orm.NewOrm()
	userAdminRoleAuthority := &models.UserAdminRoleAuthority{}
	qs := o.QueryTable("UserAdminRoleAuthority")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["userAdminRoleId"]; ok {
		qs = qs.Filter("user_admin_role_id", p["userAdminRoleId"])
	}
	if _, ok := p["authorityId"]; ok {
		qs = qs.Filter("authority_id", p["authorityId"])
	}
	qs.One(userAdminRoleAuthority)
	return userAdminRoleAuthority
}

// 添加管理员角色权限信息
func AddUserAdminRoleAuthority(input url.Values) (int64, error) {
	o := orm.NewOrm()
	var userAdminRoleAuthorities []models.UserAdminRoleAuthority

	userAdminRole := &models.UserAdminRole{}
	if _, ok := input["user_admin_role_id"]; ok {
		userAdminRole.Id = utils.Atoi64(input["user_admin_role_id"][0])
		o.Read(userAdminRole)
	}

	if _, ok := input["authority_id"]; ok {
		for _, authorityId := range input["authority_id"] {
			userAdminRoleAuthority := models.UserAdminRoleAuthority{}
			userAdminRoleAuthority.UserAdminRole = userAdminRole
			authority := &models.Authority{}
			authority.Id = utils.Atoi64(authorityId)
			o.Read(authority)
			userAdminRoleAuthority.Authority = authority
			userAdminRoleAuthorities = append(userAdminRoleAuthorities, userAdminRoleAuthority)
		}
	}

	return o.InsertMulti(1, userAdminRoleAuthorities)
}

// 编辑管理员角色权限信息
func EditUserAdminRoleAuthority(input url.Values) (int64, error) {
	o := orm.NewOrm()
	userAdminRole := models.UserAdminRole{Id: utils.Atoi64(input["id"][0])}
	m2m := o.QueryM2M(&userAdminRole, "Authorities")
	m2m.Clear()
	input["user_admin_role_id"] = []string{input["id"][0]}
	return AddUserAdminRoleAuthority(input)
}